import { useState, useCallback, useEffect, useRef, useImperativeHandle, useMemo } from 'react';
import { fjAndDgDataCode, intl, resDataFilter } from '@/utils';
import Form, { SimpleItem, GroupItem, } from 'devextreme-react/form';
import 'devextreme-react/text-area';
import { request, useModel } from 'umi';
import notify from 'devextreme/ui/notify';
import React from 'react';
import Button from 'devextreme-react/button';
import "../index.less"
import { getCpasIcon } from '@/utils/icon';
import moment from 'moment';
import ErrorBounced from '@/pages/components/ErrorBounced';
import { getFileProperties } from '../../../service';

const AttributeDgProps = ({ fjid, onCloseDrawer, fjRefreshEvent, dginfoData }: any, ref: any) => {
  const { initialState } = useModel('@@initialState');
  const { dbname, sjxmbh } = initialState?.curPart as API.CurPart;
  const { username, usercode } = initialState?.curUser as API.CurUser;
  const tplDialogRef = useRef<any>();
  const refsForm = useRef<any>();
  const [formDataObj, setFormDataObj] = useState({});

  // 获取 附件属性信息
  const fetchData = async (dataObj: any) => {
    const res = await getFileProperties(dbname, dataObj.fjid);
    if (res.success) {
      let { data } = res;
      const dateObj = moment.utc(data.LastEditDate);
      if (dateObj.isValid()) {
        data.LastEditDate = dateObj.format('YYYY-MM-DD HH:mm:ss');
      } else {
        data.LastEditDate = ' ';
      }
      setFormDataObj(data);
    }

  };

  // 自定义方法
  useImperativeHandle(ref, () => ({
    refresh: (dataobj: any) => {
      fetchData(dataobj);
    },
  }));

  const validationRules = {

    fjName: [
      { type: 'required', message: '请输入附件名称！' },
    ],
    fjsyh: [
      { type: 'required', message: '请输入索引号！' },
    ],
  }

  async function changeProperty(data: any, sjxmbh: any, fjid: string, dbname: string) {
    // const strRegex = /\.(xlsx|xls|docx|doc|jpg|png|txt|pdf|rar|rar4|zip|mp3|mp4)$/;
    // if (strRegex.test(data.fjlx)) { } else {
    //   notify({ message: "类型格式不对", type: 'error' });
    // }
    const devForm: Form = refsForm.current as Form;
    const result: any = devForm.instance.validate();
    if (result && result.isValid) {
      const body: {
        sjxmbh: string,
        dbname: string,
        fjid: string,
        fjsyh: string,
        fjName: string,
        fjlx: string,
        UserName: string | undefined,
        BZ: string
      } = {
        sjxmbh: sjxmbh,
        dbname: dbname,
        fjid: fjid,
        fjsyh: data.fjsyh,
        fjName: data.fjName,
        fjlx: data.fjlx,
        UserName: username,
        BZ: data.BZ,
      };

      const res = await request('/cpasApi/draftFjManage/updateFileProperties', {
        method: 'POST',
        data: body,
      });
      if (res.ok) {
        const resFilter = resDataFilter(res.data);
        if (resFilter.success) {
          const { reDataArr } = resFilter;
          if (reDataArr.tempError.length) {
            const resNew = fjAndDgDataCode(reDataArr.tempError[0].code);
            return notify(`${resNew}!`, 'error', 3000);
          }
          notify({ message: intl('paper.saveSuccess', '保存成功'), type: 'success' });
          // await fetchData({ fjid })
          fjRefreshEvent(true)
          // onCloseDrawer()
        } else {
          notify('保存失败', 'error', 2000);
        }
      } else {
        notify('保存失败', 'error', 2000);
      }
    }
  }

  return (
    <div style={{ height: 'calc(100% - 50px)', width: '100%' }}>
      <div style={{ width: '100%', height: '95%' }}>
        {useMemo(() => {
          return <Form formData={formDataObj}
            ref={refsForm}
            width='100%' height='100%' className='FormStyle' >
            <GroupItem
              cssClass="first-group"
              colCount={4}
              style={{ marginBottom: '10px' }}
              caption={intl('paper.info', '附件信息')}
            >
              <SimpleItem editorOptions={formDataObj} render={(e) => <span style={{ fontSize: '50px', marginLeft: '12px' }}>{getCpasIcon(e.editorOptions.fjlx, 55)}</span>} />
              <GroupItem colSpan={3}>
                <SimpleItem
                  validationRules={validationRules.fjName}
                  dataField="fjName"
                  name="fjName"
                  label={{
                    text: intl('paper.fjmc', '附件名称'),
                    location: 'top',
                  }}
                />
              </GroupItem>
            </GroupItem>
            <GroupItem cssClass="second-group" colCount={1}>
              <GroupItem caption={intl('paper.syh', '索引号')}>
                <SimpleItem
                  validationRules={validationRules.fjsyh}
                  dataField="fjsyh"
                  name="fjsyh"
                  label={{
                    text: intl('paper.fjsyh', '附件索引号'),
                    location: 'left',
                  }}
                />
              </GroupItem>

              <GroupItem caption=' '
              >
                <SimpleItem
                  dataField="fjlx"
                  name="fjlx"
                  editorType="dxTextBox"
                  label={{
                    text: intl('paper.lx', '附件类型'),
                  }}
                  editorOptions={{
                    disabled: true,
                  }}
                />
                <SimpleItem
                  dataField="UserName"
                  editorType="dxTextBox"
                  editorOptions={{
                    disabled: true,
                  }}
                  label={{
                    text: intl('paper.dgsyy', '编辑人'),
                  }}
                />
                <SimpleItem
                  dataField="LastEditDate"
                  editorType="dxTextBox"
                  editorOptions={{
                    disabled: true,
                  }}
                  label={{
                    text: intl('paper.dgsyy', '编辑时间'),
                  }}
                />
              </GroupItem>
              <GroupItem caption={'备注:'}>
                <SimpleItem
                  colSpan={2}
                  dataField="BZ"
                  editorType="dxTextArea"
                  label={{
                    visible: false,
                  }}
                  editorOptions={{ height: 150 }}
                />
              </GroupItem>
            </GroupItem>
          </Form>
        }, [formDataObj])}

      </div>
      <ErrorBounced ref={tplDialogRef} />

      <div style={{ height: '10%', display: 'flex', alignItems: 'center', }}>
        <Button
          width={88}
          type="default"
          text={intl('paper.save', '保存')}
          onClick={async () => {
            changeProperty(formDataObj, sjxmbh, fjid, dbname);
          }}
        />
        <Button
          width={88}
          text={intl('audit.cancel', '取消')}
          onClick={async () => {
            onCloseDrawer()
          }}
        />
      </div >
    </div >
  );
};



export default React.forwardRef(AttributeDgProps);
